// Load the SDK Asynchronously
(function(d) {
	var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
	
	if (d.getElementById(id)) {
		return;
	}
	
	js = d.createElement('script');
	js.id = id;
	js.async = true;
	js.src = "//connect.facebook.net/en_US/all.js";
	ref.parentNode.insertBefore(js, ref);
}(document));


// Init the SDK upon load
window.fbAsyncInit = function() {
	FB.init({
		appId : '404093396303381', // App ID
		status : true, // check login status
		cookie : true, // enable cookies to allow the server to access the session
		xfbml : true // parse XFBML
	});

	FB.getLoginStatus(function(response) {
		if (response.status === 'connected') {
			FB.api('/me', function(me) {
				if (me.name) {
					$('#auth-member-login').css("display", 'none');
					$('#auth-member').css("display", 'block');
					$('#link-logout').css("display", 'inline');
					$("#member-picture").attr("src", "https://graph.facebook.com/"+response.authResponse.userID+"/picture");
					$("#member-name").html(me.name);
					$('#auth-displayname').html(me.name);
				}
				else{
					$('#auth-displayname').html("Convidado");
				}
			});
		}
	});
	
	// respond to clicks on the login and logout links
	$('#auth-loginlink').bind('click', function() {
		FB.login(function(response){
			FB.init({
				appId : '404093396303381', // App ID
				status : true, // check login status
				cookie : true, // enable cookies to allow the server to access the session
				xfbml : true // parse XFBML
			});
			
			FB.getLoginStatus(function(response) {
				if (response.status === 'connected') {
					FB.api('/me', function(me) {
						if (me.name) {
							$('#link-logout').css("display", 'inline');
							$("#member-picture").attr("src", "https://graph.facebook.com/"+response.authResponse.userID+"/picture");
							$('#auth-displayname').html(me.name);
						}
						else{
							$('#auth-displayname').html("Convidado");
						}
					});
				}
			});
			
			$('#auth-member-login').css("display", 'none');
			$('#auth-member').css("display", 'block');
			$('#link-logout').css("display", 'inline');
		});
	});
	
	$('#auth-logoutlink').bind('click', function() {
		FB.logout(function(response){
			$('#auth-displayname').html("Convidado");
			$('#auth-member-login').css("display", 'block');
			$('#auth-member').css("display", 'none');
			$('#link-logout').css("display", 'none');
		});
	});
};